<template>
  <Layout>
    <div class="content-header">
      <h2>数据库运行状态</h2>
    </div>
    <div class="content-body">
      <!-- 加载状态 -->
      <div v-if="loading" style="text-align: center; padding: 40px; font-size: 16px; color: var(--text-secondary)">
        加载中...
      </div>

      <!-- 错误提示 -->
      <div v-if="error" style="text-align: center; padding: 40px; font-size: 16px; color: var(--danger-color)">
        {{ error }}
      </div>

      <!-- 数据展示 -->
      <template v-if="!loading && !error">
        <el-card class="stat-cards">
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="stat-card info">
                <div>
                  <div class="stat-label">数据库总数</div>
                  <div class="stat-value">{{ totalDatabases }} 个</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card success">
                <div>
                  <div class="stat-label">正常运行</div>
                  <div class="stat-value">{{ normalDatabases }} 个</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card warning">
                <div>
                  <div class="stat-label">需要关注</div>
                  <div class="stat-value">{{ warningDatabases }} 个</div>
                </div>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="stat-card" style="background: linear-gradient(135deg, #8b5cf6 0%, #7c3aed 100%)">
                <div>
                  <div class="stat-label">总QPS</div>
                  <div class="stat-value">{{ totalQPS.toLocaleString() }}</div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-card>

        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>数据库实例列表</span>
            </div>
          </template>
          
          <div class="table-toolbar">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-select 
                  v-model="filters.status"
                  placeholder="请选择状态"
                  clearable
                  style="width: 100%"
                >
                  <el-option label="全部" value="all" />
                  <el-option label="正常" value="normal" />
                  <el-option label="告警" value="warning" />
                </el-select>
              </el-col>
              
              <el-col :span="12">
                <el-input 
                  v-model="filters.search"
                  placeholder="输入数据库名称或主机地址"
                  clearable
                />
              </el-col>
              
              <el-col :span="4">
                <el-button @click="clearFilters">清除筛选</el-button>
              </el-col>
            </el-row>
          </div>

          <el-table 
            :data="paginatedDatabases" 
            style="width: 100%" 
            :default-sort="{ prop: 'name', order: 'ascending' }"
          >
            <el-table-column 
              prop="name" 
              label="数据库名称" 
              sortable 
              :sort-method="(a, b) => a.name.localeCompare(b.name)"
            >
              <template #default="scope">
                <span style="font-weight: 600; color: var(--primary-light)">
                  {{ scope.row.name }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="host" label="主机地址" />
            <el-table-column 
              prop="connections" 
              label="连接数" 
              sortable 
              :sort-method="(a, b) => a.connections - b.connections"
            >
              <template #default="scope">
                <span style="font-weight: 600">
                  {{ scope.row.connections }}
                </span>
              </template>
            </el-table-column>
            <el-table-column 
              prop="qps" 
              label="QPS" 
              sortable 
              :sort-method="(a, b) => (a.qps || 0) - (b.qps || 0)"
            >
              <template #default="scope">
                <span style="font-weight: 600; color: var(--success-color)">
                  {{ scope.row.qps?.toLocaleString() }}
                </span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" sortable>
              <template #default="scope">
                <el-tag 
                  :type="scope.row.status === 'normal' ? 'success' : 'warning'"
                >
                  {{ scope.row.status === 'normal' ? '正常' : '告警' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="uptime" label="运行时长" />
          </el-table>
        <!-- 分页组件 -->
        <Pagination
          :current-page="currentPage"
          :total-pages="totalPages"
          :page-size="pageSize"
          :total-items="filteredDatabases.length"
          @page-change="handlePageChange"
          @page-size-change="handlePageSizeChange"
        />
        </el-card>
      </template>
    </div>
  </Layout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import Layout from '../components/Layout.vue'
import Pagination from '../components/Pagination.vue'
import { databaseAPI } from '../services/api'
import type { Database } from '../types'
import type { Machine } from '../types'
import { useTableData } from '../composables/useTableData'

const databasesData = ref<Database[]>([])
const loading = ref(true)
const error = ref<string | null>(null)
const sortConfig = ref<{ key: string | null; direction: 'asc' | 'desc' }>({
  key: null,
  direction: 'asc'
})
const filters = ref({
  status: 'all',
  search: ''
})
const selectedMachine = ref<Machine | null>(null)
const showDetail = ref(false)

// 使用统一的分页逻辑
const {
  currentPage,
  pageSize,
  paginatedData: paginatedDatabases,
  totalPages,
  handlePageChange,
  handlePageSizeChange
} = useTableData({
  data: databasesData,
  filters,
  defaultSort: { key: null, direction: 'asc' },
  pageSize: 5
})

// 加载数据
const fetchDatabases = async () => {
  try {
    loading.value = true
    const response: any = await databaseAPI.getAll()
    if (response.success) {
      databasesData.value = response.data || []
    } else {
      error.value = '加载数据失败: ' + response.message
    }
    error.value = null
  } catch (err: any) {
    error.value = '加载数据失败: ' + err.message
    console.error('Failed to fetch databases:', err)
  } finally {
    loading.value = false
  }
}

// 筛选和排序后的数据
const filteredDatabases = computed(() => {
  let filtered = [...databasesData.value]

  // 状态筛选
  if (filters.value.status !== 'all') {
    filtered = filtered.filter(d => d.status === filters.value.status)
  }

  // 搜索筛选
  if (filters.value.search) {
    const searchLower = filters.value.search.toLowerCase()
    filtered = filtered.filter(d => 
      d.name.toLowerCase().includes(searchLower) ||
      d.host.includes(searchLower)
    )
  }

  // 排序
  if (sortConfig.value.key) {
    filtered.sort((a, b) => {
      const aVal = a[sortConfig.value.key as keyof Database]
      const bVal = b[sortConfig.value.key as keyof Database]
      
      if (aVal! < bVal!) return sortConfig.value.direction === 'asc' ? -1 : 1
      if (aVal! > bVal!) return sortConfig.value.direction === 'asc' ? 1 : -1
      return 0
    })
  }

  return filtered
})

// 统计数据
const totalDatabases = computed(() => databasesData.value.length)
const normalDatabases = computed(() => databasesData.value.filter(d => d.status === 'normal').length)
const warningDatabases = computed(() => databasesData.value.filter(d => d.status === 'warning').length)
const totalQPS = computed(() => databasesData.value.reduce((sum, d) => sum + (d.qps || 0), 0))

const clearFilters = () => {
  filters.value = { status: 'all', search: '' }
  sortConfig.value = { key: null, direction: 'asc' }
  currentPage.value = 1
}

// 当筛选条件改变时，重置到第一页
const resetPageOnFilterChange = () => {
  currentPage.value = 1
}

computed(() => {
  const _ = [filters.value, sortConfig.value]
  resetPageOnFilterChange()
  return _
})

onMounted(() => {
  fetchDatabases()
})
</script>
